// DOM 元素
const chatWrapper = document.querySelector('.chat-wrapper');
const messageInput = document.getElementById('messageInput');
const userList = document.getElementById('users');
const userCount = document.querySelector('.user-count');
const sendBtn = document.querySelector('.send-btn');
const fileBtn = document.querySelector('.file-btn');
const nicknameBtn = document.querySelector('.nickname-btn');
const clearBtn = document.querySelector('.clear-btn');
const toggleUsersBtn = document.querySelector('.toggle-users-btn');
const mobileOverlay = document.querySelector('.mobile-overlay');
const rightPanel = document.querySelector('.right');
const dragTip = document.querySelector('.dragtip');
const screenshotBtn = document.querySelector('.screenshot-btn');
const voiceBtn = document.querySelector('.voice-btn');
const codeBtn = document.querySelector('.code-btn');

// 模态框
const userSelectModal = document.getElementById('userSelectModal');
const userSelectList = document.getElementById('userSelectList');
const nicknameModal = document.getElementById('nicknameModal');
const nicknameInput = document.getElementById('nicknameInput');
const passwordModal = document.getElementById('passwordModal');
const roomPasswordInput = document.getElementById('roomPasswordInput');
const progressContainer = document.querySelector('.progress-container');
const progressText = document.querySelector('.progress-text');
const progressBarInner = document.querySelector('.progress-bar-inner');

// 文件传输相关
let selectedFile = null;
let selectedUsers = new Set();

// 消息存储
let messages = [];
const MAX_MESSAGES = 50;

// 连接到服务器
xchatuser.connect().catch(error => {
  console.error('Failed to connect:', error);
});

// 消息发送
function sendMessage() {
  const content = messageInput.value.trim();
  if (content) {
    xchatuser.sendMessage(content);
    messageInput.value = '';
  }
}

// 发送按钮点击
sendBtn.addEventListener('click', sendMessage);

// 输入框回车发送
function enterTxt(event) {
  if (event.keyCode === 13 && !event.shiftKey) {
    event.preventDefault();
    sendMessage();
  }
}

// 清空聊天记录
clearBtn.addEventListener('click', () => {
  if (confirm('确定要清空聊天记录吗？')) {
    messages = [];
    chatWrapper.innerHTML = '';
    // 重新添加欢迎消息
    const welcomeMessage = document.querySelector('.welcome-message');
    if (welcomeMessage) {
      chatWrapper.appendChild(welcomeMessage.cloneNode(true));
    }
  }
});

// 显示消息
function appendMessage(message) {
  // 如果是第一条消息，先清除欢迎消息
  if (messages.length === 0) {
    const welcomeMessage = chatWrapper.querySelector('.welcome-message');
    if (welcomeMessage) {
      welcomeMessage.remove();
    }
  }

  const messageDiv = document.createElement('div');
  messageDiv.className = 'message';
  if (message.userId === xchatuser.userId) {
    messageDiv.classList.add('self');
  }

  const header = document.createElement('div');
  header.className = 'message-header';
  const user = xchatuser.users.get(message.userId) || { nickname: '未知用户' };
  header.textContent = `${user.nickname} · ${formatTime(message.timestamp || Date.now())}`;

  const content = document.createElement('div');
  content.className = 'message-content';
  
  if (message.type === 'file') {
    content.className += ' file-message';
    content.innerHTML = `
      <div class="file-info">
        <div class="file-icon">
          <svg viewBox="0 0 24 24" width="24" height="24">
            <path fill="currentColor" d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z" />
          </svg>
        </div>
        <div class="file-details">
          <div class="file-name">${message.fileName}</div>
          <div class="file-size">${formatFileSize(message.fileSize)}</div>
        </div>
      </div>
      <div class="file-actions">
        <button onclick="downloadFile('${message.url}', '${message.fileName}')">
          <svg viewBox="0 0 24 24" width="16" height="16">
            <path fill="currentColor" d="M5,20H19V18H5M19,9H15V3H9V9H5L12,16L19,9Z" />
          </svg>
          下载
        </button>
      </div>
    `;
  } else if (message.type === 'code') {
    try {
      const codeData = JSON.parse(message.content);
      content.className += ' code-message';
      content.innerHTML = `
        <div class="code-block">
          <div class="code-header">
            <span class="code-language">${codeData.language}</span>
            <button class="copy-btn" onclick="copyCode(this)">复制</button>
          </div>
          <pre><code class="language-${codeData.language}">${escapeHtml(codeData.content)}</code></pre>
        </div>
      `;
    } catch (e) {
      content.textContent = message.content;
    }
  } else {
    content.textContent = message.content;
  }

  messageDiv.appendChild(header);
  messageDiv.appendChild(content);
  
  // 添加消息到数组
  messages.push(message);
  
  // 如果消息超过限制，删除最早的消息
  if (messages.length > MAX_MESSAGES) {
    messages.shift();
    const firstMessage = chatWrapper.querySelector('.message');
    if (firstMessage) {
      firstMessage.remove();
    }
  }
  
  chatWrapper.appendChild(messageDiv);
  chatWrapper.scrollTop = chatWrapper.scrollHeight;
}

// 更新用户列表
function updateUserList(users) {
  userList.innerHTML = '';
  let count = 0;
  users.forEach(user => {
    if (user.userId !== xchatuser.userId) {
      count++;
      const li = document.createElement('li');
      li.textContent = user.nickname;
      li.dataset.userId = user.userId;
      userList.appendChild(li);
    }
  });
  // 更新用户数量
  userCount.textContent = count;
}

// 文件大小格式化
function formatFileSize(bytes) {
  if (bytes < 1024) return bytes + ' B';
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
  if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
  return (bytes / (1024 * 1024 * 1024)).toFixed(1) + ' GB';
}

// 文件下载
function downloadFile(url, fileName) {
  const a = document.createElement('a');
  a.href = url;
  a.download = fileName;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

// 发送文件
async function sendFileToUsers() {
  if (!selectedFile || selectedUsers.size === 0) return;

  progressContainer.style.display = 'block';
  progressText.textContent = '正在发送...';
  progressBarInner.style.width = '0%';

  try {
    for (const userId of selectedUsers) {
      await xchatuser.sendFile(selectedFile, userId);
    }
    userSelectModal.style.display = 'none';
  } catch (error) {
    console.error('Failed to send file:', error);
    alert('发送文件失败');
  }

  selectedFile = null;
  selectedUsers.clear();
  progressContainer.style.display = 'none';
}

// 文件选择
fileBtn.addEventListener('click', () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.onchange = (e) => {
    selectedFile = e.target.files[0];
    if (selectedFile) {
      showUserSelectModal();
    }
  };
  input.click();
});

// 显示用户选择模态框
function showUserSelectModal() {
  userSelectList.innerHTML = '';
  xchatuser.users.forEach(user => {
    if (user.userId !== xchatuser.userId) {
      const label = document.createElement('label');
      label.innerHTML = `
        <input type="checkbox" value="${user.userId}">
        ${user.nickname}
      `;
      userSelectList.appendChild(label);
    }
  });
  userSelectModal.style.display = 'block';
}

// 确认发送文件
function confirmSendFile() {
  selectedUsers.clear();
  const checkboxes = userSelectList.querySelectorAll('input[type="checkbox"]:checked');
  checkboxes.forEach(checkbox => {
    selectedUsers.add(checkbox.value);
  });
  if (selectedUsers.size > 0) {
    sendFileToUsers();
  } else {
    alert('请选择至少一个接收用户');
  }
}

// 取消发送文件
function cancelSendFile() {
  selectedFile = null;
  selectedUsers.clear();
  userSelectModal.style.display = 'none';
}

// 昵称设置
nicknameBtn.addEventListener('click', () => {
  nicknameInput.value = xchatuser.nickname;
  nicknameModal.style.display = 'block';
});

// 保存昵称
function saveNickname() {
  const nickname = nicknameInput.value.trim();
  if (nickname) {
    xchatuser.saveNickname(nickname);
    nicknameModal.style.display = 'none';
  } else {
    alert('昵称不能为空');
  }
}

// 关闭昵称模态框
function closeNicknameModal() {
  nicknameModal.style.display = 'none';
}

// 提交房间密码
function submitRoomPassword() {
  const password = roomPasswordInput.value.trim();
  if (password) {
    xchatuser.submitRoomPassword(password);
  } else {
    alert('密码不能为空');
  }
}

// 移动端切换用户列表
if (toggleUsersBtn) {
  toggleUsersBtn.addEventListener('click', () => {
    rightPanel.classList.toggle('active');
    mobileOverlay.classList.toggle('active');
  });

  mobileOverlay.addEventListener('click', () => {
    rightPanel.classList.remove('active');
    mobileOverlay.classList.remove('active');
  });
}

// 拖拽发送文件
document.addEventListener('dragenter', (e) => {
  e.preventDefault();
  dragTip.classList.add('active');
});

document.addEventListener('dragover', (e) => {
  e.preventDefault();
});

document.addEventListener('dragleave', (e) => {
  e.preventDefault();
  if (e.relatedTarget === null) {
    dragTip.classList.remove('active');
  }
});

document.addEventListener('drop', (e) => {
  e.preventDefault();
  dragTip.classList.remove('active');
  
  const files = e.dataTransfer.files;
  if (files.length > 0) {
    selectedFile = files[0];
    showUserSelectModal();
  }
});

// 格式化时间
function formatTime(timestamp) {
  const date = new Date(timestamp);
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
}

// 注册回调
xchatuser.onMessage(appendMessage);
xchatuser.onOnline(updateUserList);
xchatuser.onOffline(() => {
  updateUserList(Array.from(xchatuser.users.values()));
});

xchatuser.onFileProgress(({progress}) => {
  progressBarInner.style.width = (progress * 100) + '%';
});

xchatuser.onPasswordRequired(() => {
  passwordModal.style.display = 'block';
});

xchatuser.onPasswordSuccess(() => {
  passwordModal.style.display = 'none';
  roomPasswordInput.value = '';
});

xchatuser.onPasswordError(() => {
  alert('密码错误');
  roomPasswordInput.value = '';
});

// 截图功能
screenshotBtn.addEventListener('click', async () => {
  try {
    // 创建截图提示
    const tip = document.createElement('div');
    tip.className = 'screenshot-tip';
    tip.textContent = '请选择要截图的区域';
    document.body.appendChild(tip);

    const stream = await navigator.mediaDevices.getDisplayMedia({
      preferCurrentTab: true,
      video: {
        cursor: "always"
      },
      audio: false
    });

    // 移除提示
    document.body.removeChild(tip);

    const video = document.createElement('video');
    video.srcObject = stream;
    
    // 等待视频加载
    await new Promise(resolve => {
      video.onloadedmetadata = () => {
        video.play();
        resolve();
      };
    });

    const canvas = document.createElement('canvas');
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    
    const ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0);
    
    // 停止所有轨道
    stream.getTracks().forEach(track => track.stop());
    
    // 转换为文件
    canvas.toBlob(blob => {
      const file = new File([blob], `截图_${formatTime(Date.now())}.png`, { type: 'image/png' });
      selectedFile = file;
      showUserSelectModal();
      
      // 预览截图
      const filePreview = userSelectModal.querySelector('.file-name');
      const fileSize = userSelectModal.querySelector('.file-size');
      if (filePreview && fileSize) {
        filePreview.textContent = file.name;
        fileSize.textContent = formatFileSize(file.size);
      }
    }, 'image/png', 0.95);
  } catch (error) {
    console.error('截图失败:', error);
    alert('截图失败，请检查浏览器权限设置');
  }
});

// 语音消息功能
let mediaRecorder = null;
let audioChunks = [];
let isRecording = false;

voiceBtn.addEventListener('mousedown', async () => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ 
      audio: {
        echoCancellation: true,
        noiseSuppression: true,
        sampleRate: 44100
      }
    });
    
    mediaRecorder = new MediaRecorder(stream);
    audioChunks = [];
    
    mediaRecorder.ondataavailable = (e) => {
      if (e.data.size > 0) {
        audioChunks.push(e.data);
      }
    };
    
    mediaRecorder.start();
    isRecording = true;
    voiceBtn.classList.add('recording');
    
    // 添加录音动画
    const ripple = document.createElement('div');
    ripple.className = 'voice-ripple';
    voiceBtn.appendChild(ripple);
    
  } catch (error) {
    console.error('录音失败:', error);
    alert('录音失败，请检查麦克风权限');
  }
});

voiceBtn.addEventListener('mouseup', () => {
  if (mediaRecorder && isRecording) {
    mediaRecorder.stop();
    isRecording = false;
    voiceBtn.classList.remove('recording');
    
    // 移除录音动画
    const ripple = voiceBtn.querySelector('.voice-ripple');
    if (ripple) {
      ripple.remove();
    }
    
    mediaRecorder.onstop = () => {
      const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
      const file = new File([audioBlob], `语音_${formatTime(Date.now())}.webm`, { type: 'audio/webm' });
      selectedFile = file;
      
      // 预览语音
      showUserSelectModal();
      const filePreview = userSelectModal.querySelector('.file-name');
      const fileSize = userSelectModal.querySelector('.file-size');
      if (filePreview && fileSize) {
        filePreview.textContent = file.name;
        fileSize.textContent = formatFileSize(file.size);
      }
      
      // 停止所有轨道
      mediaRecorder.stream.getTracks().forEach(track => track.stop());
    };
  }
});

// 代码片段功能
codeBtn.addEventListener('click', () => {
  const codeModal = document.createElement('div');
  codeModal.className = 'modal code-modal';
  codeModal.innerHTML = `
    <div class="modal-content">
      <h3>发送代码片段</h3>
      <div class="code-input-container">
        <select class="language-select">
          <option value="text">纯文本</option>
          <option value="javascript">JavaScript</option>
          <option value="python">Python</option>
          <option value="java">Java</option>
          <option value="cpp">C++</option>
          <option value="html">HTML</option>
          <option value="css">CSS</option>
          <option value="json">JSON</option>
          <option value="sql">SQL</option>
        </select>
        <textarea class="code-input" placeholder="在此输入代码..." rows="10"></textarea>
      </div>
      <div class="modal-footer">
        <button class="cancel-btn">取消</button>
        <button class="confirm-btn">发送</button>
      </div>
    </div>
  `;
  
  document.body.appendChild(codeModal);
  
  const textarea = codeModal.querySelector('.code-input');
  const languageSelect = codeModal.querySelector('.language-select');
  const cancelBtn = codeModal.querySelector('.cancel-btn');
  const confirmBtn = codeModal.querySelector('.confirm-btn');
  
  codeModal.style.display = 'block';
  textarea.focus();
  
  cancelBtn.onclick = () => {
    document.body.removeChild(codeModal);
  };
  
  confirmBtn.onclick = () => {
    const code = textarea.value.trim();
    const language = languageSelect.value;
    
    if (code) {
      const message = {
        type: 'code',
        content: code,
        language: language,
        timestamp: Date.now()
      };
      xchatuser.sendMessage(JSON.stringify(message));
      document.body.removeChild(codeModal);
    }
  };
});

// HTML转义函数
function escapeHtml(text) {
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}

// 复制代码函数
function copyCode(button) {
  const codeBlock = button.closest('.code-block');
  const code = codeBlock.querySelector('code').textContent;
  
  navigator.clipboard.writeText(code).then(() => {
    const originalText = button.textContent;
    button.textContent = '已复制';
    button.disabled = true;
    
    setTimeout(() => {
      button.textContent = originalText;
      button.disabled = false;
    }, 2000);
  }).catch(err => {
    console.error('复制失败:', err);
    alert('复制失败，请手动复制');
  });
} 